import { defineStore } from 'pinia';
// import userApi from '../../api/user'
const userApi = {}
const prefix = 'haipi_'
export default defineStore('user',{
	state: ()=> {
		return {
			isLogin:false,
			userinfo: null,
			token: localStorage.getItem(prefix+'token') || ''
		}
	},
	actions: {
		...userApi,
		register(data){
			return userApi.register(data).then(response => {
				if(response.data.token){
					this.isLogin = true
					this.token = response.data.token
					localStorage.setItem(prefix + 'token',this.token)
				}
				uni.showToast({
					icon:'success',
					title: '注册成功'
				})
				return response
			}, ()=>{
				console.log('err')
			})
		},
		login(data){
			return userApi.login(data).then(response => {
				if(response.data.token){
					this.isLogin = true
					this.token = response.data.token
					localStorage.setItem(prefix + 'token',this.token)
				}
				uni.showToast({
					icon:'success',
					title: '登录成功'
				})
				return response
			})
		},
		async getUserInfo(){
			if(!this.token){
				this.logout()
				return 
			}
			let ret = await userApi.getUserInfo({token: this.token})
		
			if(!ret || !ret.data){
				this.logout()
			}else{
				this.userinfo = ret.data
				this.isLogin = true
			}
		},
		logout(){
			this.token = ''
			this.userinfo = null
			this.isLogin = false
		},
	},
	
})